package main

import (
	"os"

	"github.com/op/go-logging"
	"github.com/valyala/fasthttp"
	"gopkg.in/alecthomas/kingpin.v2"
)

var (
	confdir = kingpin.Flag("confdir", "config directory.").Short('c').String()
	log     = logging.MustGetLogger("godeye")
	format  = logging.MustStringFormatter(
		`%{color}%{time:2006-01-02 15:04:05} [%{level:.4s}] > %{color:reset} %{message}`,
	)
)

func checkErr(err error, desc string) {
	if err != nil {
		log.Errorf("[%s]: %v", desc, err)
	}
}

func main() {
	kingpin.Parse()
	//读取配置文件
	conf := &config{}
	ReadDir(*confdir, conf)
	//日志格式配置
	if conf.log_file == "" {
		bk := logging.NewLogBackend(os.Stderr, "", 0)
		bkFormatter := logging.NewBackendFormatter(bk, format)
		logging.SetBackend(bkFormatter)
	} else {
		file, err := os.OpenFile(conf.log_file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
		checkErr(err, "open log_file error!")
		defer file.Close()
		bk := logging.NewLogBackend(file, "", 0)
		bkFormatter := logging.NewBackendFormatter(bk, format)
		logging.SetBackend(bkFormatter)
	}
	//初始化exporter
	host := &Host{tags: conf.tags}
	proc := &Proc{tags: conf.tags}
	//读取模块
	for _, mdl := range conf.modules {
		switch mdl {
		case "host_base":
			hb := HostBase{interval: conf.interval}
			host.metrics = append(host.metrics, hb)
		case "proc_base":
			pb := ProcBase{interval: conf.interval, confdir: *confdir}
			proc.metrics = append(proc.metrics, pb)
		case "net_check":
			nc := NetCheck{cks: conf.net_check}
			host.metrics = append(host.metrics, nc)
		case "ping":
			pg := Ping{ips: conf.ping_ips}
			host.metrics = append(host.metrics, pg)
		default:
			log.Error("no such module!")
		}
	}
	//定时读取指标数据
	go host.refresh(conf.interval)
	defer host.Close()
	go proc.refresh(conf.interval)
	defer proc.Close()
	//启动prometheus服务
	if conf.prome_addr != "" {
		log.Infof("start prometheus export on %s", conf.prome_addr)
		log.Infof("using tags: %v", conf.tags)
		fasthttp.ListenAndServe(conf.prome_addr, func(ctx *fasthttp.RequestCtx) {
			switch string(ctx.Path()) {
			case "/host":
				b := host.export()
				ctx.Success("text/plain; version=0.0.4", []byte(b))
			case "/export":
				b := proc.export()
				ctx.Success("text/plain; version=0.0.4", []byte(b))
			default:
				ctx.Error("", fasthttp.StatusNotFound)
			}
		})
	}
}
